package com.school.campus.service.impl;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.school.campus.mapper.ActivityMapper;
import com.school.campus.domain.Activity;
import com.school.campus.service.IActivityService;

/**
 * 校内活动Service业务层处理
 *
 * @author wwj
 * @date 2025-11-06
 */
@Service
public class ActivityServiceImpl implements IActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

//    /**
//     * 查询校内活动
//     *
//     * @param id 校内活动主键
//     * @return 校内活动
//     */
//    @Override
//    public Activity selectActivityById(String id) {
//        return activityMapper.selectActivityById(id);
//    }
//
//    /**
//     * 查询校内活动列表
//     *
//     * @param activity 校内活动
//     * @return 校内活动
//     */
//    @Override
//    public List<Activity> selectActivityList(Activity activity) {
//        return activityMapper.selectActivityList(activity);
//    }

    /**
     * 新增校内活动
     *
     * @param activity 校内活动
     * @return 结果
     */
    @Override
    public int insertActivity(Activity activity) {
        activity.setActivityStatus(0L);
        activity.setCurrentSignUpNum(0);
        return activityMapper.insertActivity(activity);
    }

    /**
     * 修改校内活动
     *
     * @param activity 校内活动
     * @return 结果
     */
    @Override
    public int updateActivity(Activity activity) {
        return activityMapper.updateActivity(activity);
    }

    /**
     * 批量删除校内活动
     *
     * @param ids 需要删除的校内活动主键
     * @return 结果
     */
    @Override
    public int deleteActivityByIds(String[] ids) {
        return activityMapper.deleteActivityByIds(ids);
    }

    /**
     * 删除校内活动信息
     *
     * @param id 校内活动主键
     * @return 结果
     */
    @Override
    public int deleteActivityById(String id) {
        return activityMapper.deleteActivityById(id);
    }
    /**
     * 处理活动
     *
     * @param id           活动ID
     * @param activityStatus 活动状态
     * @return 结果
     */
    @Override
    public int dealWithActivity(String id, Long activityStatus) {

        return activityMapper.updateActivityById(id,activityStatus);
    }


    /**
     * 获取活动实时状态（结合Redis缓存）
     */
    public Long getRealTimeActivityStatus(Activity activity) {
        String cacheKey = "activity:realtime:status:" + activity.getId();

        // 尝试从Redis获取缓存的状态
        Object cachedStatus = redisTemplate.opsForValue().get(cacheKey);
        if (cachedStatus != null) {
            return (Long) cachedStatus;
        }

        // 计算实时状态
        Long realStatus = calculateRealTimeStatus(activity);

        // 将状态缓存到Redis，设置过期时间（例如5分钟）
        redisTemplate.opsForValue().set(cacheKey, realStatus, 300, TimeUnit.SECONDS);

        return realStatus;
    }

    /**
     * 计算活动的实时状态
     */
    private Long calculateRealTimeStatus(Activity activity) {
        Long currentStatus = activity.getActivityStatus();
        Date now = new Date();

        // 只对已发布(1)和进行中(2)的活动进行状态计算
        if (currentStatus == 1 || currentStatus == 2) {
            if (now.after(activity.getEndTime())) {
                return 3L; // 已结束
            } else if (now.after(activity.getStartTime()) && now.before(activity.getEndTime())) {
                return 2L; // 进行中
            }
        }
        return currentStatus;
    }

    /**
     * 定时更新活动状态缓存
     */
    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void refreshActivityStatusCache() {
        // 查询所有需要检查状态的活动
        Activity queryCondition = new Activity();
        List<Activity> activities = activityMapper.selectActivityList(queryCondition);

        for (Activity activity : activities) {
            Long realStatus = calculateRealTimeStatus(activity);

            // 如果状态发生变化，则更新缓存
            if (!realStatus.equals(activity.getActivityStatus())) {
                String cacheKey = "activity:realtime:status:" + activity.getId();
                redisTemplate.opsForValue().set(cacheKey, realStatus, 300, TimeUnit.SECONDS);
            }
        }
    }

    /**
     * 重写查询活动列表方法，返回包含实时状态的活动列表
     */
    @Override
    public List<Activity> selectActivityList(Activity activity) {
        List<Activity> activities = activityMapper.selectActivityList(activity);
        Date now = new Date();

        for (Activity act : activities) {
            // 动态计算并设置实时状态
            Long realStatus = calculateRealTimeStatus(act);
            act.setActivityStatus(realStatus);
        }

        return activities;
    }

    /**
     * 重写查询单个活动方法
     */
    @Override
    public Activity selectActivityById(String id) {
        Activity activity = activityMapper.selectActivityById(id);
        if (activity != null) {
            Long realStatus = calculateRealTimeStatus(activity);
            activity.setActivityStatus(realStatus);
        }
        return activity;
    }
}
